﻿using ContactSMS.Commons.Responses;
using ContactSMS.WebAPI.Common;
using ContactSMS.WebAPI.Controllers.Request;
using ContactSMS.WebAPI.Controllers.Responses;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ContactSMS.WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class TokenController : ControllerBase
    {
        private readonly TokenService _tokenService;

        public TokenController(TokenService tokenService)
        {
            this._tokenService = tokenService;
        }

        [HttpPost]
        public IActionResult Refresh([FromBody] RefreshTokenRequest request)
        {
            // 验证刷新令牌
            //var isValid = ValidateRefreshToken(request.RefreshToken, request.UserName); // 使用新的刷新令牌验证逻辑

            //if (!isValid)
            //{
            //    return Unauthorized("Invalid refresh token");
            //}
            try
            {
                var principal = _tokenService.GetPrincipalFromExpiredToken(request.AccessToken);
                var username = principal.Identity.Name;
                var newAccessToken = _tokenService.GenerateAccessToken(principal.Claims);
                var newRefreshToken = _tokenService.GenerateRefreshToken(username);
                ServiceResponse<TokenResponse> resp = new ServiceResponse<TokenResponse>();
                var tokenResponse = new TokenResponse()
                {
                    AccessToken = newAccessToken,
                    RefreshToken = newRefreshToken
                };
                resp.Success = true;
                resp.Message = "获取成功";
                resp.Data = tokenResponse;
                return Ok(resp);
            }
            catch
            {
                return Unauthorized();
            }
        }

        private bool ValidateRefreshToken(string refreshToken, string username)
        {
            // 解析和验证刷新令牌
            try
            {
                // 从刷新令牌中获取声明信息
                var principal = _tokenService.GetPrincipalFromExpiredToken(refreshToken);

                // 从声明中提取用户名并进行匹配
                var tokenUsername = principal.Identity?.Name;

                // 检查令牌中的用户名是否匹配
                return tokenUsername == username;
            }
            catch (Exception)
            {
                // 如果出现异常，表示令牌无效
                return false;
            }
        }
    }
}
